package com.alliky.core.util;

import android.util.Base64;

import com.blankj.utilcode.util.EncodeUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * ================================================
 *
 * @Description: 描述
 * @Author: wxianing
 * @Date: 2023/4/4 15:51
 * ================================================
 */
public class AesUtil {

    private static final String TAG = "AesUtil";

    public static String AESKey = "Sm5NQnpOMG9KT1oy";
    private static String AESIv = "";

    private static final String ECB_PKCS5_PADDING = "AES/ECB/PKCS5Padding";
    private static final String AES = "AES";

    private static boolean isEncode = true;

    public static String setSign(Map<String, Object> params) {
        return setSign(params, isEncode);
    }

    public static String setSign2(Map<String, String> params) {
        return setSign2(params, isEncode);
    }

    public static String setSign(Map<String, Object> params, boolean encode) {

        Set<String> keysSet = params.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer temp = new StringBuffer();
        boolean first = true;
        for (Object key : keys) {
            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = String.valueOf(value);
            }
            if (encode) {
                try {
                    temp.append(URLDecoder.decode(valueString, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                temp.append(valueString);
            }
        }

        String result = encrypt(temp.toString(), AESKey);
        return result;
    }

    public static String setSign2(Map<String, String> params, boolean encode) {

        Set<String> keysSet = params.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer temp = new StringBuffer();
        boolean first = true;
        for (Object key : keys) {
            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = String.valueOf(value);
            }
            if (encode) {
                try {
                    temp.append(URLDecoder.decode(valueString, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                temp.append(valueString);
            }
        }

        String result = encrypt(temp.toString(), AESKey);
        return result;
    }


    /**
     * AES 加密
     *
     * @param strKey  加密密钥
     * @param content 待加密内容
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String strKey) {
        try {
            byte[] raw = strKey.getBytes();
            // 创建AES密钥
            SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
            // 创建密码器
            Cipher cipher = Cipher.getInstance(ECB_PKCS5_PADDING);
            // 初始化加密器
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            // 执行加密操作
            byte[] cipherText = cipher.doFinal(content.getBytes());
            //加密之后转Base64
            String strBase64Content = Base64.encodeToString(cipherText, Base64.DEFAULT); // encode it by BASE64 again
            //去掉无用斜杠
            strBase64Content = strBase64Content.replaceAll(System.getProperty("line.separator"), "");
            //转成Base64字节
            byte[] result = EncodeUtils.base64Encode(strBase64Content);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * AES 解密
     *
     * @param strKey  解密密钥
     * @param content 待解密内容
     * @return 返回Base64转码后的加密数据
     */
    public static String decrypt(String content, String strKey) {
        try {
            content = new String(EncodeUtils.base64Decode(content));
            byte[] raw = strKey.getBytes("ASCII");
            // 创建AES秘钥
            SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
            // 创建密码器
            Cipher cipher = Cipher.getInstance(ECB_PKCS5_PADDING);
            // 创建偏移量
//            IvParameterSpec iv = new IvParameterSpec(mstrIvParameter.getBytes());
            // 初始化解密器
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            // 执行解密操作
            byte[] cipherText = Base64.decode(content, Base64.DEFAULT); // decode by BASE64 first
            //Log.d(TAG, "BASE64 decode result(): " + cipherText.toString());
            byte[] clearText = cipher.doFinal(cipherText);
            String strClearText = new String(clearText);
            //Log.d(TAG, "decrypt result: " + strClearText);
            return strClearText;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
